import { computed, ref, watch } from 'vue'

import { back, catchFn, wait } from '@/libs/common'
import { editUserInfo, addFriend, editFriend, saveByFriend } from './api'
import { topMessage } from '@/components/TopMessage/data'
import {
  checkUserInfo,
  fillInFriend,
  inviteCode,
  updateUserInfo,
  userInfo,
  userInfoFull,
} from '@/libs/user'
import { imagePath } from '@/libs/file-utils'
import { updateFriend } from '@/pages/community/friend/list/data'
import { getFriendGroupList } from '@/pages/community/friend/list/api'
import { updateUserDetail } from '../info/data'

const genderList: {
  value: 1 | 2
  name: '男' | '女'
  img: string
}[] = [
  {
    value: 1,
    name: '男',
    img: imagePath('user/edit-info/gender-1.png'),
  },
  {
    value: 2,
    name: '女',
    img: imagePath('user/edit-info/gender-2.png'),
  },
]
const gender = ref<0 | 1 | 2>(0)

const nickname = ref('')
/** 好友群组列表 */
const groupList = ref<T_FriendGroup[]>([])
const groupIdx = ref(-1)

const birthday = ref('2000-01-01')
const year = ref('2000')
const month = ref('1')
const day = ref('1')
const birthtime = ref('12:00')

const place = ref<string[]>([])
const placeStr = computed(() => {
  const temp = place.value.join(',')

  return temp.length < 3 ? '' : temp
})

/** MBTI列表 */
const mbtiList = [
  'INTJ',
  'INTP',
  'ENTJ',
  'ENTP',
  'INFJ',
  'INFP',
  'ENFJ',
  'ENFP',
  'ISTJ',
  'ISFJ',
  'ESTJ',
  'ESFJ',
  'ISTP',
  'ISFP',
  'ESFP',
]
/** 当前选择MBTI */
const curMBTIIdx = ref(-1)

/** 当前修改好友 */
const curFriend = ref<T_Friend>()

export {
  genderList,
  gender,
  nickname,
  groupList,
  groupIdx,
  birthday,
  year,
  month,
  day,
  birthtime,
  place,
  placeStr,
  mbtiList,
  curMBTIIdx,
  curFriend,
}

watch(birthday, val => ([year.value, month.value, day.value] = val.split('-')), { immediate: true })

/**
 * 初始化
 */
const init = () =>
  catchFn(async () => {
    const { data } = await getFriendGroupList()

    groupList.value = data.filter(item => item.id !== 0)

    if (fillInFriend.value) return
    else if (curFriend.value) {
      // 好友
      gender.value = curFriend.value.gender
      nickname.value = curFriend.value.nickname
      groupIdx.value = groupList.value.findIndex(item => item.id === curFriend.value?.groupId)
      birthday.value = curFriend.value.birthday || '2000-01-01'
      place.value = [
        curFriend.value.province || '',
        curFriend.value.city || '',
        curFriend.value.district || '',
      ]
      curMBTIIdx.value = mbtiList.findIndex(item => item === curFriend.value?.mbtiType)
    } else {
      // 用户
      gender.value = userInfo.value?.gender || 0
      nickname.value = userInfo.value?.nickname || ''
      birthday.value = userInfo.value?.birthday || '2000-01-01'
      birthtime.value = userInfo.value?.birthtime || '12:00'
      place.value = [
        userInfo.value?.province || '',
        userInfo.value?.city || '',
        userInfo.value?.district || '',
      ]
    }
  })

/**
 * 更新用户信息
 */
const confirm = () =>
  catchFn(async () => {
    if (gender.value === 0) throw '请选择性别'
    if (!nickname.value) throw '请输入姓名'

    if (fillInFriend.value) {
      if (groupIdx.value === -1) throw '请选择关系'

      await saveByFriend({
        groupId: groupList.value[groupIdx.value].id,
        nickname: nickname.value,
        gender: gender.value,
        birthday: birthday.value,
        province: place.value[0] || '',
        city: place.value[1] || '',
        district: place.value[2] || '',
        mbtiType: mbtiList[curMBTIIdx.value] || '',
        inviteCode: inviteCode.value,
      })

      topMessage.success('修改成功')

      fillInFriend.value = false

      wait(800).then(() =>
        uni.reLaunch({
          url: userInfoFull.value ? '/pages/main/index' : '/pages/user/edit-info/index',
        }),
      )
    } else if (curFriend.value) {
      if (groupIdx.value === -1) throw '请选择关系'

      // 好友
      if (curFriend.value.isNew) {
        await addFriend({
          groupId: groupList.value[groupIdx.value].id,
          nickname: nickname.value,
          gender: gender.value,
          birthday: birthday.value,
          province: place.value[0] || '',
          city: place.value[1] || '',
          district: place.value[2] || '',
          mbtiType: mbtiList[curMBTIIdx.value] || '',
        })

        topMessage.success('添加成功')
      } else {
        await editFriend({
          id: curFriend.value.id,
          groupId: groupList.value[groupIdx.value].id,
          nickname: nickname.value,
          gender: gender.value,
          birthday: birthday.value,
          province: place.value[0] || '',
          city: place.value[1] || '',
          district: place.value[2] || '',
          mbtiType: mbtiList[curMBTIIdx.value] || '',
        })

        topMessage.success('修改成功')
      }

      updateFriend()
      wait(800).then(() => back('/pages/user/edit-info/index'))
    } else {
      // 用户
      await editUserInfo({
        nickname: nickname.value,
        gender: gender.value,
        birthday: birthday.value,
        birthtime: birthtime.value,
        province: place.value[0] || '',
        city: place.value[1] || '',
        district: place.value[2] || '',
      })
      await updateUserInfo()
      await checkUserInfo()

      topMessage.success('修改成功')

      wait(800).then(() => {
        if (getCurrentPages().length > 1) {
          updateUserDetail()
          back()
        } else {
          uni.redirectTo({ url: '/pages/quiz/mbti/choose/index' })
        }
      })
    }
  })

/**
 * 还原状态
 */
const clear = () => {
  gender.value = 0
  nickname.value = ''
  groupIdx.value = -1
  birthday.value = '2000-01-01'
  birthtime.value = '12:00'
  place.value = []
  curMBTIIdx.value = -1
  curFriend.value = undefined
}

export { init, confirm, clear }
